package cron

import (
	"context"

	"code.bydev.io/frameworks/byone/core/logc"
	"code.bydev.io/frameworks/byone/core/logx"
)

func (d *Domain) ApprovedActionImageHandler(ctx context.Context) error {
	logc.Infow(ctx, "ApprovedActionImageHandler begin")
	limit := 300
	initRecords, err := d.adminRepo.GetLatestMonthInitStatusRecords(ctx, limit)
	if err != nil {
		logc.Errorw(ctx, "s.kycActionImage.GetLatestMonthInitStatusRecords error", logc.Field("err", err))
		return err
	}
	if len(initRecords) == 0 {
		logc.Infow(ctx, "no filter records")
		return nil
	}
	for _, record := range initRecords {
		ctx := logx.ContextWithFields(ctx, logx.Field("id", record.Id), logx.Field("idempotentId", record.IdempotentId))
		// 判断记录是否已完成
		isDone, err := d.adminRepo.IsRecordDone(ctx, record.Id)
		if err != nil {
			logc.Errorw(ctx, "ApprovedActionImageHandler IsRecordDone error", logc.Field("err", err))
			return err
		}
		if isDone {
			logc.Infow(ctx, "ApprovedActionImageHandler is done", logc.Field("record", record))
			continue
		}
		// 判断记录是否已通过审批的记录
		action, err := d.adminRepo.GetActionByIdempotentID(ctx, record.IdempotentId)
		if err != nil {
			logc.Errorw(ctx, "s.adminRepo.GetActionByIdempotentID error", logc.Field("err", err))
			return err
		}
		// 处理已通过审批图片
		if action.Decision == 1 {
			err = d.handleImage(ctx, record)
			if err != nil {
				logc.Errorw(ctx, "s.handleImage error", logc.Field("record.Id", record.Id), logc.Field("err", err))
			}
		} else {
			err = d.adminRepo.MarkImageNotFound(ctx, record)
			if err != nil {
				logc.Errorw(ctx, "s.adminRepo.MarkImageNotFound error", logc.Field("record.Id", record.Id), logc.Field("err", err))
			}
		}
	}
	logc.Infow(ctx, "ActionImageHandler end")
	return nil
}
